<?php
/**
 *   OPENSHOP 会员管理程序
 * 
 *   @link        http://baison.com.cn
 *   @copyright   Baison, Inc.
 *   @package     OpenShop
 *   @version     $Id: users.php,v 1.0 2009/06/17 08:36:58 modified $
 *   @author      FillBag <fillbag@hotmail.com>
 */

define('IN_OS', true);

require(dirname(__FILE__) . '/includes/init.php');

/*------------------------------------------------------ */
//-- 用户帐号列表
/*------------------------------------------------------ */

if ($_REQUEST['act'] == 'list')
{
	//检查权限
	admin_priv();
		
    $sql = "SELECT rank_id, rank_name, min_points FROM ".$os->table('user_rank')." ORDER BY min_points ASC ";
    $rs = $db->query($sql);

    $ranks = array();
    while ($row = $db->FetchRow($rs))
    {
        $ranks[$row['rank_id']] = $row['rank_name'];
    }

    $smarty->assign('user_ranks',   $ranks);
    $smarty->assign('ur_here',      '客户列表');
    //$smarty->assign('action_link',  array('text' => '客户添加', 'href'=>'users.php?act=add'));

    $reg_week = trim($_REQUEST['reg_week']);
    
    $user_list = user_list($reg_week);

    $smarty->assign('user_list',    $user_list['user_list']);
    $smarty->assign('filter',       $user_list['filter']);
    $smarty->assign('record_count', $user_list['record_count']);
    $smarty->assign('page_count',   $user_list['page_count']);
    $smarty->assign('full_page',    1);
    $smarty->assign('sort_user_id', '<img src="images/sort_desc.gif">');

    assign_query_info();    
    $smarty->display("users_list.tpl");   
}

/*------------------------------------------------------ */
//-- ajax返回用户列表
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'query')
{
    $user_list = user_list();

    $smarty->assign('user_list',    $user_list['user_list']);
    $smarty->assign('filter',       $user_list['filter']);
    $smarty->assign('record_count', $user_list['record_count']);
    $smarty->assign('page_count',   $user_list['page_count']);

    $sort_flag  = sort_flag($user_list['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);

    make_json_result($smarty->fetch('users_list.tpl'), '', array('filter' => $user_list['filter'], 'page_count' => $user_list['page_count']));
}

/*------------------------------------------------------ */
//-- 添加客户帐号
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'add')
{
    /* 检查权限 */
    admin_priv('add_users');

    $user = array(  'rank_points'   => $_CFG['register_points'],
                    'pay_points'    => $_CFG['register_points'],
                    'sex'           => 0,
                    'credit_line'   => 0
                    );

    /* 生成后台添加额外用户属性 */
    $sql = "SELECT * FROM  ".$os->table('user_attribute')." order by attr_type asc";
    $user_attrs = $db->getAll($sql);
    $html = '';
    
    foreach ($user_attrs AS $key => $val)
    {
        $html .= "<tr><td class='label'>";
        $html .= "$val[attr_name]:</td><td>";
        if ($val['attr_input_type'] == 0)
        {
            $html .= '<input name="other['.$val['attr_id'].']" type="text"  size="25" />';
        }
        elseif ($val['attr_input_type'] == 2)
        {
            $html .= '<textarea name="other['.$val['attr_id'].']" rows="3" cols="25"></textarea>';
        }
        elseif ($val['attr_type'] == 2 & $val['attr_input_type'] == 1){
            $attr_values = explode("\n", $val['attr_values']);
            foreach ($attr_values AS $opt)
            {
                $opt   = trim(htmlspecialchars($opt));
                $html .= "<input type='checkbox' name='other[".$val['attr_id']."][]' value='".$opt."'>&nbsp;&nbsp;".$opt."&nbsp;&nbsp;";   
            }
        }else{
            $html .= '<select name="other['.$val['attr_id'].']">';
            $html .= '<option value="">请选择...</option>';

            $attr_values = explode("\n", $val['attr_values']);

            foreach ($attr_values AS $opt)
            {
                $opt    = trim(htmlspecialchars($opt));

                $html   .= '<option value="' . $opt . '">' . $opt . '</option>';
            }
            $html .= '</select> ';
        }
        $html .= '</td></tr>';
    }
                        
    $smarty->assign('ur_here',          '客户添加');
    $smarty->assign('action_link',      array('text' => '客户列表', 'href'=>'users.php?act=list'));
    $smarty->assign('form_action',      'insert');
    $smarty->assign('user',             $user);
    $smarty->assign('extra_attribute',  $html);
    $smarty->assign('special_ranks',    get_rank_list(true));
    
    assign_query_info();    
    $smarty->display("user_info.tpl");      
}

/*------------------------------------------------------ */
//-- 添加客户帐号
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'insert')
{
    /* 检查权限 */
    admin_priv('add_users');
    
    $username = empty($_POST['username']) ? '' : trim($_POST['username']);
    $nickname = empty($_POST['nickname']) ? $username : trim($_POST['nickname']);
    $password = empty($_POST['password']) ? '' : trim($_POST['password']);
    $email = empty($_POST['email']) ? '' : trim($_POST['email']);
    $sex = empty($_POST['sex']) ? 0 : intval($_POST['sex']);
    $sex = in_array($sex, array(0, 1, 2)) ? $sex : 0;
    $birthday = $_POST['birthdayYear'] . '-' .  $_POST['birthdayMonth'] . '-' . $_POST['birthdayDay'];
    $rank = empty($_POST['user_rank']) ? 0 : intval($_POST['user_rank']);
    $credit_line = empty($_POST['credit_line']) ? 0 : floatval($_POST['credit_line']);

    $users =& init_users(); 
  // die( $username. $password.  $email );
    $email=$username;
    if (!$users->add_user($username, $password, $email))
    {
        /* 插入客户数据失败 */
        if ($users->error == ERR_INVALID_USERNAME)
        {
            $msg = '无效的客户名';
        }
        elseif ($users->error == ERR_USERNAME_NOT_ALLOW)
        {
            $msg = '客户名不允许注册';
        }
        elseif ($users->error == ERR_USERNAME_EXISTS)
        {
            $msg = '已经存在一个相同的客户名。';
        }
        elseif ($users->error == ERR_INVALID_EMAIL)
        {
            $msg = '无效的email地址';
        }
        elseif ($users->error == ERR_EMAIL_NOT_ALLOW)
        {
            $msg = '邮件不允许';
        }
        elseif ($users->error == ERR_EMAIL_EXISTS)
        {
            $msg = '该邮件地址已经存在。';
        }
        else
        {
            //die('Error:'.$users->error_msg());
        }
        sys_msg($msg, 1);
    }

    /* 注册送积分 */
    if (!empty($GLOBALS['_CFG']['register_points']))
    {
        log_account_change($_SESSION['user_id'], 0, 0, $GLOBALS['_CFG']['register_points'], $GLOBALS['_CFG']['register_points'], '注册送积分');
    }

    /* 更新客户的其它信息 */
    $other =  array();
    $other['credit_line'] = $credit_line;
    $other['user_rank']  = $rank;
    $other['sex']        = $sex;
    $other['birthday']   = $birthday;
    $other['nick_name']  = $nickname;
    $other['reg_time']   = gmtime();
    
    foreach ($_POST['other'] as $key=>$val)
    {
        if (intval($key) < 1 & !empty($val))
        {
            $other[$key] = htmlspecialchars(trim($val));
        }
    }
    $db->autoExecute($os->table('users'), $other, 'UPDATE', "user_name = '$username'");

    /* 添加额外用户属性 */
    $sql_id = "SELECT user_id FROM ".$os->table('users')." WHERE user_name = '".$username."'";
    $user_id = $db->getOne($sql_id);
    
    $others = $_POST['other']; 
    if ($others)
    {
        foreach ($others as $key=>$val)
        {
            //删除非法key值
            if (intval($key) > 0 ) {
                    // 插入后台用户添加属性数值
                    if (is_array($val) & !empty($val)) {
                        foreach($val as $val)
                        {
                            $t_value .= $val.' ';
                        }
                        $val = $t_value;
                    }
                    $value = $val;  
                    $sqln = "INSERT INTO " .$GLOBALS['os']->table('user_attribute_value'). " (user_id, attr_id, attr_value)".
                            "VALUES (".$user_id. "," .$key.",'". $value ."')";
                    $db->query($sqln);                   
            }
        }
    }
    
    /* 记录管理员操作 */
    admin_log($_POST['username'], 'add', 'users');

    /* 提示信息 */
    $link[] = array('text' => '返回上一页', 'href'=>'users.php?act=list');
    sys_msg(sprintf('客户账号 %s 已经添加成功。', htmlspecialchars(stripslashes($_POST['username']))), 0, $link);
}

/*------------------------------------------------------ */
//-- 编辑用户帐号
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'edit')
{
    /* 检查权限 */
    admin_priv('edit_users');

    $sql = "SELECT u.user_name,u.nick_name, u.sex, u.birthday, u.pay_points, u.rank_points, u.user_rank , u.user_money, u.frozen_money, u.credit_line, u.parent_id, u2.user_name as parent_username, u.qq,
    u.msn, u.office_phone, u.home_phone, u.mobile_phone ".
        " FROM " .$os->table('users'). " u LEFT JOIN " . $os->table('users') . " u2 ON u.parent_id = u2.user_id WHERE u.user_id='$_GET[id]'";

    $row = $db->GetRow($sql);
    $row['user_name'] = addslashes($row['user_name']);
    $users  =& init_users();
    $user   = $users->get_user_info($row['user_name']);

    $sql = "SELECT u.user_id, u.nick_name, u.sex, u.birthday, u.pay_points, u.rank_points, u.user_rank , u.user_money, u.frozen_money, u.credit_line, u.parent_id, u2.user_name as parent_username, u.qq, u.msn,
    u.office_phone, u.home_phone, u.mobile_phone ".
        " FROM " .$os->table('users'). " u LEFT JOIN " . $os->table('users') . " u2 ON u.parent_id = u2.user_id WHERE u.user_id='$_GET[id]'";
	
    $row = $db->GetRow($sql);

    if ($row)
    {
        $user['user_id']        = $row['user_id'];
        $user['nick_name']      = $row['nick_name'];
        $user['sex']            = $row['sex'];
        $user['birthday']       = date($row['birthday']);
        $user['pay_points']     = $row['pay_points'];
        $user['rank_points']    = $row['rank_points'];
        $user['user_rank']      = $row['user_rank'];
        $user['user_money']     = $row['user_money'];
        $user['frozen_money']   = $row['frozen_money'];
        $user['credit_line']    = $row['credit_line'];
        $user['formated_user_money'] = price_format($row['user_money']);
        $user['formated_frozen_money'] = price_format($row['frozen_money']);
        $user['parent_id']      = $row['parent_id'];
        $user['parent_username']= $row['parent_username'];
        $user['qq']             = $row['qq'];
        $user['msn']            = $row['msn'];
        $user['office_phone']   = $row['office_phone'];
        $user['home_phone']     = $row['home_phone'];
        $user['mobile_phone']   = $row['mobile_phone'];
    }
    else
    {
        $user['sex']            = 0;
        $user['pay_points']     = 0;
        $user['rank_points']    = 0;
        $user['user_money']     = 0;
        $user['frozen_money']   = 0;
        $user['credit_line']    = 0;
        $user['formated_user_money'] = price_format(0);
        $user['formated_frozen_money'] = price_format(0);
    }   
    
    $smarty->assign('ur_here',          '编辑客户账号');
    $smarty->assign('action_link',      array('text' => '客户列表', 'href'=>'users.php?act=list&' . list_link_postfix()));
    $smarty->assign('user',             $user);
    $smarty->assign('form_action',      'update');
    $smarty->assign('special_ranks',    get_rank_list(true));
    
    assign_query_info();
    $smarty->display("user_info.tpl");    
}
/*------------------------------------------------------ */
//-- 编辑用户特殊属性
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'edit_attr')
{
    /* 检查权限 */
    admin_priv('edit_users_attr');

    $sql = " select u_attr.attr_id, attr_name, attr_input_type,attr_type,attr_values,sort_order,attr_value".
		  " from ". $os->table('user_attribute'). "as u_attr" .
		  " left join ".$os->table('user_attribute_value')." as u_value ".
		  " on u_value.attr_id = u_attr.attr_id and user_id=".$_GET[id];
    $user_attrs = $db->getAll($sql);
    assign_query_info();
    $smarty->assign('ur_here',          '编辑客户账号');
    $smarty->assign('action_link',      array('text' => '用户列表', 'href'=>'users.php?act=list&' . list_link_postfix()));
    $smarty->assign('user_attrs',       $user_attrs);
    $smarty->assign('user_id',          $_GET[id]);
    $smarty->assign('user_attr_html',	build_user_attr_html($_GET[id]));
    
    $smarty->display("user_attribute_value.tpl");      
}

/*------------------------------------------------------ */
//-- 更新用户特殊属性
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'update_attr')
{
    /* 检查权限 */
    admin_priv('edit_users_attr');
    
    $username = empty($_POST['username']) ? '' : trim($_POST['username']);
    
    /* 更新用户属性值 */
    $sql = " select u_attr.attr_id, attr_name, attr_input_type,attr_type,attr_values,sort_order,attr_value".
		  " from ". $os->table('user_attribute'). "as u_attr" .
		  " left join ". $os->table('user_attribute_value')." as u_value ".
		  " on u_value.attr_id = u_attr.attr_id and user_id = ".$_POST['id'];

    $user_attrs = $db->getAll($sql);
    
    $sql1 = "DELETE FROM " . $os->table('user_attribute_value').
		  " WHERE user_id = ".$_POST['id'];
    $db->query($sql1);
    
    $array = NULL;
    foreach ($user_attrs AS $attr)
    {
		$v = $_POST[$attr['attr_id']]==null?"":$_POST[$attr['attr_id']];
        if (is_array($v) & !empty($v)) {
            foreach($v as $value)
            {
                $t_value .= $value.' ';
            }
            $v = $t_value;
        }
        $sqln = "INSERT INTO " .$os->table('user_attribute_value'). " (user_id, attr_id, attr_value)".
        "VALUES (".$_POST['id']. "," .$attr['attr_id'].",'". $v ."')";
        $db->query($sqln);
    }

    /* 记录管理员操作 */
    admin_log($username, 'edit', 'user_attribute');

    /* 提示信息 */
    $links[0]['text']    = '返回客户账号列表';
    $links[0]['href']    = 'users.php?act=list';
    $links[1]['text']    = '返回上一页';
    $links[1]['href']    = 'javascript:history.back()';

    sys_msg('编辑客户信息已经成功。', 0, $links);
} 
/*------------------------------------------------------ */
//-- 更新用户帐号
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'update')
{
    /* 检查权限 */
    admin_priv('edit_users');
    
    $username = empty($_POST['username']) ? '' : trim($_POST['username']);
    $nickname = empty($_POST['nickname']) ? '' : trim($_POST['nickname']);
    $password = empty($_POST['password']) ? '' : trim($_POST['password']);
    $email = empty($_POST['email']) ? '' : trim($_POST['email']);
    $sex = empty($_POST['sex']) ? 0 : intval($_POST['sex']);
    $sex = in_array($sex, array(0, 1, 2)) ? $sex : 0;
    $birthday = $_POST['birthdayYear'] . '-' .  $_POST['birthdayMonth'] . '-' . $_POST['birthdayDay'];
    $rank = empty($_POST['user_rank']) ? 0 : intval($_POST['user_rank']);
    $credit_line = empty($_POST['credit_line']) ? 0 : floatval($_POST['credit_line']);

    $users  =& init_users();

    if (!$users->edit_user(array('username'=>$username, 'password'=>$password, 'email'=>$email, 'gender'=>$sex, 'bday'=>$birthday ), 1))
    {
        if ($users->error == ERR_EMAIL_EXISTS)
        {
            $msg = '该邮件地址已经存在。';
        }
        else
        {
            $msg = '修改客户资料失败。';
        }
        sys_msg($msg, 1);
    }

    /* 更新客户的其它信息 */
    $other =  array();
    $other['credit_line'] = $credit_line;
    $other['user_rank'] = $rank;
    $other['nick_name'] = $nickname;
    foreach ($_POST['other'] as $key=>$val)
    {
        if (!empty($val))
        {
            $other[$key] = htmlspecialchars(trim($val));
        }
    }
    $db->autoExecute($os->table('users'), $other, 'UPDATE', "user_name = '$username'");

    /* 记录管理员操作 */
    admin_log($username, 'edit', 'users');

    /* 提示信息 */
    $links[0]['text']    = '返回客户账号列表';
    $links[0]['href']    = 'users.php?act=list&' . list_link_postfix();
    $links[1]['text']    = '返回上一页';
    $links[1]['href']    = 'javascript:history.back()';

    sys_msg('编辑客户信息已经成功。', 0, $links);
}

/*------------------------------------------------------ */
//-- 批量删除客户帐号
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'batch_remove')
{
    /* 检查权限 */
    admin_priv('drop_users');

    if (isset($_POST['checkboxes']))
    {
        $sql = "SELECT user_name FROM " . $os->table('users') . " WHERE user_id " . db_create_in($_POST['checkboxes']);
        $col = $db->getCol($sql);
        $usernames = implode(',',addslashes_deep($col));
        $count = count($col);
        /* 通过插件来删除用户 */
        $users =& init_users();
        $users->remove_user($col);

        admin_log($usernames, 'batch_remove', 'users');

        $lnk[] = array('text' => '返回上一页', 'href'=>'users.php?act=list');
        sys_msg(sprintf('已经成功删除了 %d 个客户账号。', $count), 0, $lnk);
    }
    else
    {
        $lnk[] = array('text' => '返回上一页', 'href'=>'users.php?act=list');
        sys_msg('您现在没有需要删除的客户！', 0, $lnk);
    }
}

/* 编辑用户名 */
elseif ($_REQUEST['act'] == 'edit_username')
{
    /* 检查权限 */
    check_authz_json('edit_users');

    $username = empty($_REQUEST['val']) ? '' : json_str_iconv(trim($_REQUEST['val']));
    $id = empty($_REQUEST['id']) ? 0 : intval($_REQUEST['id']);

    if ($id == 0)
    {
        make_json_error('NO USER ID');
        return;
    }

    if ($username == '')
    {
        make_json_error('您客户名称不能为空！');
        return;
    }

    $users =& init_users();

    if ($users->edit_user($id, $username))
    {
        if ($_CFG['integrate_code'] != 'osshop')
        {
            /* 更新商城客户表 */
            $db->query('UPDATE ' .$os->table('users'). " SET user_name = '$username' WHERE user_id = '$id'");
        }

        admin_log(addslashes($username), 'edit', 'users');
        make_json_result(stripcslashes($username));
    }
    else
    {
        $msg = ($users->error == ERR_USERNAME_EXISTS) ? '已经存在一个相同的客户名。' : '修改客户资料失败。';
        make_json_error($msg);
    }
}

/*------------------------------------------------------ */
//-- 编辑email
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'edit_email')
{
	
    /* 检查权限 */
    check_authz_json('edit_users');

    $id = empty($_REQUEST['id']) ? 0 : intval($_REQUEST['id']);
    $email = empty($_REQUEST['val']) ? '' : json_str_iconv(trim($_REQUEST['val']));

    $users =& init_users();

    $sql = "SELECT user_name FROM " . $os->table('users') . " WHERE user_id = '$id'";
    $username = $db->getOne($sql);

	
    if (is_email($email))
    {
        if ($users->edit_user(array('username'=>$username, 'email'=>$email)))
        {
            admin_log(addslashes($username), 'edit', 'users');
            make_json_result(stripcslashes($email));
        }
        else
        {
            $msg = ($users->error == ERR_EMAIL_EXISTS) ? '该EMail已经存在' : 'EMail更新失败';
            make_json_error($msg);
        }
    }
    else
    {
        make_json_error('更新EMail失败');
    }
}

/*------------------------------------------------------ */
//-- 删除客户帐号
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'remove')
{
    /* 检查权限 */
    admin_priv('drop_users');

    $sql = "SELECT user_name FROM " . $os->table('users') . " WHERE user_id = '" . $_GET['id'] . "'";
    $username = $db->getOne($sql);
    /* 通过插件来删除用户 */
    $users =& init_users();
    $users->remove_user($username); //已经删除用户所有数据

    /* 记录管理员操作 */
    admin_log(addslashes($username), 'remove', 'users');

    /* 提示信息 */
    $link[] = array('text' => '返回上一页', 'href'=>'users.php?act=list');
    sys_msg(sprintf('客户账号 %s 已经删除成功。', $username), 0, $link);
}

/*------------------------------------------------------ */
//--  收货地址查看
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'address_list')
{
    /* 检查权限 */
    admin_priv('view_address_list');
	$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
    $sql = "SELECT a.*, c.region_name AS country_name, p.region_name AS province, ct.region_name AS city_name, d.region_name AS district_name ".
           " FROM " .$os->table('user_address'). " as a ".
           " LEFT JOIN " . $os->table('region') . " AS c ON c.region_id = a.country " .
           " LEFT JOIN " . $os->table('region') . " AS p ON p.region_id = a.province " .
           " LEFT JOIN " . $os->table('region') . " AS ct ON ct.region_id = a.city " .
           " LEFT JOIN " . $os->table('region') . " AS d ON d.region_id = a.district " .
           " WHERE user_id='$id'";
    $address = $db->getAll($sql);
    $smarty->assign('address',          $address);
    
    assign_query_info();
    
    $smarty->assign('ur_here',          '收货地址');
    $smarty->assign('action_link',      array('text' => '客户列表', 'href'=>'users.php?act=list&' . list_link_postfix()));
    
    $smarty->display("user_address_list.tpl");    
}

/*------------------------------------------------------ */
//-- 脱离推荐关系
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'remove_parent')
{
    /* 检查权限 */
    admin_priv('drop_users_parent');

    $sql = "UPDATE " . $os->table('users') . " SET parent_id = 0 WHERE user_id = '" . $_GET['id'] . "'";
    $db->query($sql);

    /* 记录管理员操作 */
    $sql = "SELECT user_name FROM " . $os->table('users') . " WHERE user_id = '" . $_GET['id'] . "'";
    $username = $db->getOne($sql);
    admin_log(addslashes($username), 'edit', 'users');

    /* 提示信息 */
    $link[] = array('text' => '返回上一页', 'href'=>'users.php?act=list');
    sys_msg(sprintf('编辑客户信息已经成功。', $username), 0, $link);
}


/**
 *  返回用户列表数据
 *
 * @access  public
 * @param
 *
 * @return void
 */
function user_list($reg_week = 0)
{
    $result = get_filter();
    if ($result === false)
    {
        /* 过滤条件 */
        $filter['keywords'] = empty($_REQUEST['keywords']) ? '' : trim($_REQUEST['keywords']);
        if ($_REQUEST['is_ajax'] == 1)
        {
            $filter['keywords'] = json_str_iconv($filter['keywords']);
        }

        $filter['nick_name'] = empty($_REQUEST['nick_name']) ? '' : trim($_REQUEST['nick_name']);
        
        $filter['rank'] = empty($_REQUEST['rank']) ? 0 : intval($_REQUEST['rank']);
        $filter['pay_points_gt'] = empty($_REQUEST['pay_points_gt']) ? 0 : intval($_REQUEST['pay_points_gt']);
        $filter['pay_points_lt'] = empty($_REQUEST['pay_points_lt']) ? 0 : intval($_REQUEST['pay_points_lt']);

        $filter['sort_by']    = empty($_REQUEST['sort_by'])    ? 'user_id' : trim($_REQUEST['sort_by']);
        $filter['sort_order'] = empty($_REQUEST['sort_order']) ? 'DESC'     : trim($_REQUEST['sort_order']);

        $ex_where = ' WHERE 1 ';
        if ($filter['keywords'])
        {
            $ex_where .= " AND user_name LIKE '%" . mysql_like_quote($filter['keywords']) ."%'";
        }
    
        if ($filter['nick_name'])
        {
            $ex_where .= " AND nick_name LIKE '%" . mysql_like_quote($filter['nick_name']) ."%'";
        }
        if ($filter['rank'])
        {
            $sql = "SELECT min_points, max_points, special_rank FROM ".$GLOBALS['os']->table('user_rank')." WHERE rank_id = '$filter[rank]'";
            $row = $GLOBALS['db']->getRow($sql);
            if ($row['special_rank'] > 0)
            {
                /* 特殊等级 */
                $ex_where .= " AND user_rank = '$filter[rank]' ";
            }
            else
            {
                $ex_where .= " AND rank_points >= " . intval($row['min_points']) . " AND rank_points < " . intval($row['max_points']);
            }
        }
        if ($filter['pay_points_gt'])
        {
             $ex_where .= " AND pay_points >= '$filter[pay_points_gt]' ";
        }
        if ($filter['pay_points_lt'])
        {
            $ex_where .= " AND pay_points < '$filter[pay_points_lt]' ";
        }
        
        /* 过滤7天内注册的用户 */
        if ($reg_week == 1)
        {
        	$cur_time = gmtime();
            $ex_where .=" AND reg_time + 3600*24*7 >= ".$cur_time;
        }        

        $filter['record_count'] = $GLOBALS['db']->getOne("SELECT COUNT(*) FROM " . $GLOBALS['os']->table('users') . $ex_where);

        /* 分页大小 */
        $filter = page_and_size($filter);
        $sql = "SELECT user_id, user_name, nick_name, email, is_validated, user_money, frozen_money, rank_points, pay_points, reg_time ".
                " FROM " . $GLOBALS['os']->table('users') . $ex_where .
                " ORDER by " . $filter['sort_by'] . ' ' . $filter['sort_order'] .
                " LIMIT " . $filter['start'] . ',' . $filter['page_size'];

        $filter['keywords'] = stripslashes($filter['keywords']);
        set_filter($filter, $sql);
    }
    else
    {
        $sql    = $result['sql'];
        $filter = $result['filter'];
    }

    $user_list = $GLOBALS['db']->getAll($sql);

    $count = count($user_list);
    for ($i=0; $i<$count; $i++)
    {
        $user_list[$i]['reg_time'] = local_date($GLOBALS['_CFG']['date_format'], $user_list[$i]['reg_time']);
    }

    $arr = array('user_list' => $user_list, 'filter' => $filter,
        'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);

    return $arr;
}
/**
 * 根据用户属性构造用户属性表单
 *
 * @access  public
 * @param   int     $cat_id     分类编号
 * @param   int     $goods_id   商品编号
 * @return  string
 */
function build_user_attr_html($user_id)
{
    $sql = " select u_attr.attr_id, attr_name, attr_input_type,attr_type,attr_values,sort_order,attr_value".
		  " from ". $GLOBALS['os']->table('user_attribute'). "as u_attr" .
		  " left join ".$GLOBALS['os']->table('user_attribute_value')." as u_value ".
		  " on u_value.attr_id = u_attr.attr_id and u_value.user_id =".$user_id." order by attr_type asc";
    $attr = $GLOBALS['db']->GetAll($sql);
    
    $html = '<table width="100%" id="attrTable">';
    $spec = 0;

    foreach ($attr AS $key => $val)
    {
        $html .= "<tr><td class='label'>";
//        if ($val['attr_type'] == 1 || $val['attr_type'] == 2)
//        {
//            $html .= ($spec != $val['attr_id']) ?
//                "<a href='javascript:;' onclick='addSpec(this)'>[+]</a>" :
//                "<a href='javascript:;' onclick='removeSpec(this)'>[-]</a>";
//            $spec = $val['attr_id'];
//        };

        //$html .= "$val[attr_name]</td><td><input type='hidden' name='$val[attr_id]' value='$val[attr_id]' />";
		$html .= "$val[attr_name]</td><td>";
        if ($val['attr_input_type'] == 0)
        {
            $html .= '<input name="'.$val['attr_id'].'" type="text" value="' .htmlspecialchars($val['attr_value']). '" size="40" /> ';
        }
        elseif ($val['attr_input_type'] == 2)
        {
            $html .= '<textarea name="'.$val['attr_id'].'" rows="3" cols="40">' .htmlspecialchars($val['attr_value']). '</textarea>';
        }
        elseif ($val['attr_type'] == 2 & $val['attr_input_type'] == 1){
        	$attr_values = explode("\n", $val['attr_values']);
        	$attr_value  = explode(" ", $val['attr_value']);
        	foreach ($attr_values AS $opt)
            {
            	$opt   = trim(htmlspecialchars($opt));
            	$is_checked = in_array($opt,$attr_value)?'checked':'';
                $html .= "<input type='checkbox' name='".$val['attr_id']."[]' value='".$opt."'".$is_checked." >&nbsp;&nbsp;".$opt."&nbsp;&nbsp;";	
            }
        }else{
            $html .= '<select name="'.$val['attr_id'].'">';
            $html .= '<option value="">' .$GLOBALS['_LANG']['select_please']. '</option>';

            $attr_values = explode("\n", $val['attr_values']);

            foreach ($attr_values AS $opt)
            {
                $opt    = trim(htmlspecialchars($opt));

                $html   .= ($val['attr_value'] != $opt) ?
                    '<option value="' . $opt . '">' . $opt . '</option>' :
                    '<option value="' . $opt . '" selected="selected">' . $opt . '</option>';
            }
            $html .= '</select> ';
        }

//        $html .= ($val['attr_type'] == 1 || $val['attr_type'] == 2) ?
//            $GLOBALS['_LANG']['spec_price'].' <input type="text" name="attr_price_list[]" value="' . $val['attr_price'] . '" size="5" maxlength="10" />' :
//            ' <input type="hidden" name="attr_price_list[]" value="0" />';

        $html .= '</td></tr>';
    }

    $html .= '</table>';

    return $html;
}
?>